//
//  HomeViewController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/5/30.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "HomeViewController.h"
#import "XRCarouselView.h"
#import "CenterMenuView.h"

#import "CLHomeHeader.h"

#import "FirstHomeCell.h"
#import "homeCollectionViewCell.h"
#import "SearchViewController.h"

#import "RechargeController.h"
#import "OilRechargeController.h"
#import "ShopDetailsController.h"
#import "RecommendedController.h"
#import "LocationServeViewController.h"
#import "AddressManagerController.h"
#import "LocationServeManager.h"
#import "LocationServeManager.h"
#import "ReadWriteLocationCity.h"
#import "GoodListsModel.h"
#import "ShopDetailsController.h"

//间距
#define MAR_WIDTH 5

@interface HomeViewController ()<XRCarouselViewDelegate,CenterMenuViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIAlertViewDelegate,CLLocationManagerDelegate>
{
    TopPullRefreshAnaimation *gifHeader;
    MBProgressHUD *progressHUD;
    NSDictionary *_urlDict;
    
    BOOL _JudgeFirstLocationCity;
    
    NSString *_cityString;
}


@property(nonatomic,strong)XRCarouselView *XrCarouselView;
@property(nonatomic,strong)CenterMenuView *menuView;

@property(nonatomic,strong)UICollectionView *homeCollectionView;

@property(nonatomic,strong)UILabel *sectionFirstLabel;
@property(nonatomic,strong)UILabel *sectionTwoLabel;

@property(nonatomic,strong)NSArray *menuTitleArr;

@property(nonatomic,strong)MBProgressHUD *HUD;

@property(nonatomic,strong)NSMutableArray *goodsListArray;

@end

@implementation HomeViewController

static NSString * const firstReuseIdentifier =  @"firstReuseIdentifier";
static NSString * const secondReuseIdentifier=  @"secondReuseIdentifier";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self getGoodsListsRequestData];
    
    NSString *locationCityString = [ReadWriteLocationCity ReadLocatinoCity];
    if (locationCityString.length) {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem LocationCityBarButtonItemWithImage:[UIImage imageNamed:@"selectCity"] highImage:nil target:self action:@selector(setLocationServeController) forControlEvents:UIControlEventTouchUpInside title:locationCityString];
    } else {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem LocationCityBarButtonItemWithImage:[UIImage imageNamed:@"selectCity"] highImage:nil target:self action:@selector(setLocationServeController) forControlEvents:UIControlEventTouchUpInside title:@"定位"];
        
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithBackgroundImage:[UIImage imageNamed:@"shousuo"] highBackgroundImage:nil target:self action:@selector(searchDidClick) title:nil];
    
    [self addMainCollectionView];

    [LocationServeManager sharedLocationServeManager].delegate = self;
    
    _JudgeFirstLocationCity = YES;
    
    [self judgeAppVersion];
}

#pragma mark 手机版本检测
- (void)judgeAppVersion {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString* versionNum = [infoDict objectForKey:@"CFBundleVersion"];
        NSLog(@"%@",versionNum);
        [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:@{} AndMenthodName:@"http://itunes.apple.com/lookup?id=1107627163" completeBlock:^(id object) {
            NSArray *array = object[@"results"];
            NSLog(@"%@",[array.firstObject objectForKey:@"version"]);
            
            if(array && array.firstObject && [array.firstObject objectForKey:@"version"])
            {
                NSString *note = [array.firstObject objectForKey:@"releaseNotes"];
                
                if ([[array.firstObject objectForKey:@"version"]  compare:versionNum options:NSNumericSearch] == NSOrderedDescending){
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"有新版本了!赶快更新吧,第一时间体验新功能!" message:note preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            
                            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/yi-le-gou-wu-ba/id1107627163?mt=8"];
                            [[UIApplication sharedApplication] openURL:url];
                            
                        }];
                        
                        [alert addAction:SettingAction];
                        
                        
                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"稍后"style:UIAlertActionStyleCancel handler:nil];
                        [alert addAction:cancelAction];
                        
                        [self presentViewController:alert animated:YES completion:nil];
                    });
                }
            }
        }];
    });
}

#pragma mark 手机定位
- (void)setLocationServeController {
    LocationServeViewController *locationVC = [[LocationServeViewController alloc] init];
    UINavigationController *locationServe = [[UINavigationController alloc] initWithRootViewController:locationVC];
    [self presentViewController:locationServe animated:YES completion:nil];
}

#pragma mark - CLLocationManangerDelegate
//定位成功以后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    [[LocationServeManager sharedLocationServeManager] stop];
    CLLocation* location = locations.lastObject;
    [self reverseGeocoder:location];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%s",__func__);
}

#pragma mark Geocoder
//反地理编码
- (void)reverseGeocoder:(CLLocation *)currentLocation {
    
    if (!_JudgeFirstLocationCity) {
        return;
    }
    
    CLGeocoder* geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if(error || placemarks.count == 0){
            NSLog(@"error = %@",error);
        }else{
            CLPlacemark* placemark = placemarks.firstObject;
            
            NSString *appCityString = [NSString stringWithFormat:@"%@",[ReadWriteLocationCity ReadLocatinoCity]];
            
            NSLog(@"%@",[[placemark addressDictionary] objectForKey:@"City"]);
            
            NSString *string = [[placemark addressDictionary] objectForKey:@"City"];
            NSInteger length = string.length;
            _cityString = [string substringWithRange:NSMakeRange(0, length - 1)];
            
            [ReadWriteLocationCity saveLocationString:_cityString];
            
            NSLog(@"%@-------%@",appCityString,_cityString);
            if ([appCityString isEqualToString:_cityString]) {
                return;
            }
            
            NSString *TitleString = [NSString stringWithFormat:@"检测到您当前位置为:%@",[[placemark addressDictionary] objectForKey:@"City"]];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:TitleString message:@"是否切换城市" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 100101;
            [alert show];
            
            
        }
        
    }];
    
    _JudgeFirstLocationCity = NO;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 100101) {
        if (buttonIndex == 1) {
            NSLog(@"%@",_cityString);
            [ReadWriteLocationCity saveLocationCity:_cityString];
            self.navigationItem.leftBarButtonItem = [UIBarButtonItem LocationCityBarButtonItemWithImage:[UIImage imageNamed:@"selectCity"] highImage:nil target:self action:@selector(setLocationServeController) forControlEvents:UIControlEventTouchUpInside title:_cityString];
        }
    }
}


/**
 *  搜索按钮点击方法
 */
- (void)searchDidClick
{
    NSLog(@"searchDidClick");
    SearchViewController *search = [[SearchViewController alloc] init];
    [self.navigationController pushForm:self.navigationController pushToAndHidden:search];
}

- (void)addMainCollectionView
{
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    flowlayout.minimumLineSpacing = 0;
    flowlayout.minimumInteritemSpacing = 0;
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
     UICollectionView *homeCollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,WIDTH, HEIGHT-112) collectionViewLayout:flowlayout];
    self.homeCollectionView = homeCollectView;
    _homeCollectionView.delegate = self;
    _homeCollectionView.dataSource = self;
    _homeCollectionView.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:_homeCollectionView];
    
    //自适应大小
//    _homeCollectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    
    //注册cell
    [self.homeCollectionView registerClass:[FirstHomeCell class] forCellWithReuseIdentifier:firstReuseIdentifier];
    [self.homeCollectionView registerClass:[homeCollectionViewCell class] forCellWithReuseIdentifier:secondReuseIdentifier];
//    注册表头
    [self.homeCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"homeHeaderView"];
//    [self.homeCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionFirstView"];
    [self.homeCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionTwoView"];
}


#pragma mark >>>>>>>>>获取商品列表
- (void)getGoodsListsRequestData
{
    
    NSDictionary *params = @{@"p":[NSString stringWithFormat:@"%@",@(1)]};
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/goods/appGoodLists" completeBlock:^(id object) {
        if (JudgeBackDataCode) {
            
            //             NSLog(@"%@",object);
            NSDictionary *tempDict = object[@"data"];
            NSArray *arr = [tempDict objectForKey:@"list"];
            _urlDict = tempDict[@"picprex"];
            
            //            NSLog(@"%@",_urlDict);
            for (NSDictionary *dict in arr) {
                GoodListsModel *goodListsModel = [[GoodListsModel alloc] initWithDictionary:dict error:nil];
                if (goodListsModel) {
                    [self.goodsListArray addObject:goodListsModel];
                    
                }
            }
            
        }
        //菊花隐藏
        [progressHUD hide:YES];
        [_homeCollectionView reloadData];
        
    }];
    
}

#pragma mark>>>>>>>>DataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0 ) {
        return 4;
    }else {
        if (self.goodsListArray.count) {
            return 8;
        } else {
            return 0;
        }
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0 ) {
        
        FirstHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:firstReuseIdentifier forIndexPath:indexPath];
        cell.actImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"yiyuanjingpai_%ld.jpg",indexPath.item]];
        
        return cell;
        
    }else{
        
        homeCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:secondReuseIdentifier forIndexPath:indexPath];
        
        if (!self.goodsListArray.count) {
            return cell;
        }
        
        GoodListsModel *goodListsModel = self.goodsListArray[indexPath.item];
        
        NSString *string = [NSString stringWithFormat:@"%@%@",_urlDict[@"m"],goodListsModel.picurl];
        [cell.productImage sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"goodsLoadJGG.jpg"]];
        cell.productImage.contentMode = UIViewContentModeScaleToFill;
        
        cell.productName.text = goodListsModel.title;
        cell.price.text = [NSString stringWithFormat:@"专享价: %@",goodListsModel.huiyuanjia];
        cell.backgroundColor = [UIColor whiteColor];
        return cell;

    }

}

#pragma mark>>>>>>>>>>>delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==1) {
       
        //商品详情
        GoodListsModel *goodListsModel = self.goodsListArray[indexPath.item];
        ShopDetailsController *detailsVC = [[ShopDetailsController alloc] init];
        detailsVC.goodsId = goodListsModel.replaceID;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:detailsVC];
        
    }else{

        //弹框
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"功能正在建设,敬请期待!" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消");
        }];
        
        [alert addAction:cancle];
        [self presentViewController:alert animated:YES completion:nil];
        
    }

}

//header组头大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        //头部视图size           轮播      menu         快报 标题
        return CGSizeMake(WIDTH,HEIGHT/5+HEIGHT/4+12+50*2+5);
    }else{
        return CGSizeMake(WIDTH,50);
    }
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(WIDTH/2-2, HEIGHT/6);
    }else{
        return CGSizeMake(WIDTH/2-2, HEIGHT/2.8);
    }
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(1,1,1,1);
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
       
        UICollectionReusableView *reusableView;
        
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { //

            if (indexPath.section == 0) {
                //头部视图
                reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"homeHeaderView" forIndexPath:indexPath];
                [self addHeaderCycleView:reusableView];
                [self addCenterMenuView:reusableView];

            }else {
                reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"sectionTwoView" forIndexPath:indexPath];
                [reusableView addSubview:self.sectionTwoLabel];
            }
            
            return reusableView;
        }
    return  nil;
}

#pragma mark>>>>>>>>>>轮播
- (void)addHeaderCycleView:(UICollectionReusableView *)reusableView
{
    //轮播
    NSArray *imageArr = @[
                          [UIImage imageNamed:@"HomeCycle0.jpg"],
                          [UIImage imageNamed:@"HomeCycle1.jpg"],
                          [UIImage imageNamed:@"HomeCycle2.jpg"]
                          ];
    if (self.XrCarouselView == nil) {
        _XrCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/5) imageArray:imageArr];
        
        _XrCarouselView.delegate = self;
        _XrCarouselView.time = 2;
        [reusableView addSubview:_XrCarouselView];
    }
    
}


#pragma mark>>>>>>>>菜单栏 //section 0 的组头
- (void)addCenterMenuView:(UICollectionReusableView *)reusableView
{
    if (self.menuView == nil) {
        self.menuView = [[CenterMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_XrCarouselView.frame), WIDTH, HEIGHT/4+12) MenuArr:self.menuTitleArr];
        _menuView.backgroundColor = [UIColor whiteColor];
        [reusableView addSubview:_menuView];
        _menuView.delegate = self;
    
        CLHomeHeader *header = [[CLHomeHeader alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(_menuView.frame)+1,WIDTH,50)];
        header.newses = @[@[@"刘梦遥今天中午吃大米饭",@"吃的是香菇加鸡肉"],@[@"我爱你我爱你,鸟我吗?",@"今天下雨了我被淋湿了哈哈哈哈哈哈"]];
        header.cliclCelllable1 = ^{
            NSLog(@"点击了广告1");
        };
        header.cliclCelllable2 = ^{
            NSLog(@"点击了广告2");
        };
        [reusableView addSubview:header];
        
        
        
        
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(header.frame)+4, WIDTH,50)];
        [reusableView addSubview:label];
        label.text = @"   一元夺宝";
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor lightGrayColor];
        label.backgroundColor = [UIColor whiteColor];
    }

}

//View代理方法
#pragma mark >>>>>>>>>>> menu .轮播 . 代理方法
- (void)homeMenuDidSelectedAtIndex:(NSInteger)index
{
    if (index == 10) {
        RechargeController *rechargeVC = [[RechargeController alloc] init];
        rechargeVC.title = @"话费充值";
        [self.navigationController pushForm:self.navigationController pushToAndHidden:rechargeVC];
    }else if (index == 11) {
        
        OilRechargeController*oilVC = [[OilRechargeController alloc] init];
        oilVC.title = @"油卡充值";
        [self.navigationController pushForm:self.navigationController pushToAndHidden:oilVC];
        
    }else if(index == 13){
        
        RecommendedController*recommendedVC = [[RecommendedController alloc] init];
        recommendedVC.title = @"精品推荐";
        [self.navigationController pushForm:self.navigationController pushToAndHidden:recommendedVC];
    } else if (index == 14) {
        
    } else{
        
        AddressManagerController *AddressManagerVC = [[AddressManagerController alloc] init];
        [self.navigationController pushForm:self.navigationController pushToAndHidden:AddressManagerVC];
        
    }
    
}

//轮播点击代理方法
- (void)carouselView:(XRCarouselView *)carouselView didClickImage:(NSInteger)index
{
    NSLog(@"carouselView: %ld",index);
}


#pragma mark>>>>>>>>>>>>> 懒加载
- (NSArray *)menuTitleArr
{
    if (!_menuTitleArr) {
        _menuTitleArr = @[@"话费充值",@"石油充值",@"微商专区",@"精品推荐",@"一元夺宝",@"竞拍",@"活动专区",@"更多分类"];
    }
    return _menuTitleArr;
}

- (UILabel *)sectionFirstLabel
{
    if (!_sectionFirstLabel) {
        _sectionFirstLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,MAR_WIDTH, WIDTH, HEIGHT/15-MAR_WIDTH)];
        _sectionFirstLabel.text = @"   竞拍";
        _sectionFirstLabel.font = [UIFont systemFontOfSize:14];
        _sectionFirstLabel.textColor = [UIColor lightGrayColor];
        _sectionFirstLabel.backgroundColor = [UIColor whiteColor];
    }
    return _sectionFirstLabel;
}
//HEIGHT/15-MAR_WIDTH/2
- (UILabel *)sectionTwoLabel
{
    if (!_sectionTwoLabel) {
        _sectionTwoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,3, WIDTH,50-3)];
        _sectionTwoLabel.text = @"   精品推荐";
        _sectionTwoLabel.font = [UIFont systemFontOfSize:14];
        _sectionTwoLabel.textColor = [UIColor lightGrayColor];
        _sectionTwoLabel.backgroundColor = [UIColor whiteColor];
    }
    return _sectionTwoLabel;
}

- (NSMutableArray *)goodsListArray {
    if (!_goodsListArray) {
        _goodsListArray = [NSMutableArray array];
    }
    return _goodsListArray;
}



@end
